# coding:utf8
import json

from rest_framework import serializers

from .models import BookInfo, HeroInfo


class BookInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        # 指明该序列化器处理的数据字段从模型类BookInfo参考生成
        model = BookInfo
        # 指明该序列化器包含模型类中的哪些字段，'__all__'指明包含所有字段
        # fields = '__all__'
        fields = ['id', 'btitle', 'bpub_date', 'bread', 'bcomment', 'is_delete']
        # read_only_fields = ('id', 'bread', 'bcomment')
        # 优先级比上面的高
        extra_kwargs = {
            'bread': {'min_value': 0, 'required': True},
            'bcomment': {'max_value': 0, 'required': True}
        }


class HeroInfoModelSerializer(serializers.ModelSerializer):
    hbook = BookInfoModelSerializer()

    class Meta:
        model = HeroInfo
        exclude = ['id']
        # 默认ModelSerializer使用主键作为关联字段，但是我们可以使用depth来简单的生成嵌套表示，
        depth = 1


class BookInfoSerializer(serializers.Serializer):
    def about_django(value):
        if 'django' not in value.lower():
            raise serializers.ValidationError('不是Django的图书')

    """图书数据序列化器"""
    id = serializers.IntegerField(label='ID', read_only=True, )
    btitle = serializers.CharField(label='名称', max_length=20)
    bpub_date = serializers.DateField(label='发布日期', required=False)
    bread = serializers.IntegerField(label='阅读量', required=False)
    bcomment = serializers.IntegerField(label='评论量', required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate_btitle(self, value):
        if 'django' not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

    def validate(self, attrs):
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if bread and bcomment:
            if bread < bcomment:
                raise serializers.ValidationError('阅读量小于评论量')
        return attrs

    def create(self, validated_data):
        """新建"""
        # print("validated_data:{}".format(validated_data))
        # print(**validated_data)
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """更新，instance为要更新的对象实例"""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance


class HeroInfoSerializer(serializers.Serializer):
    """英雄数据序列化器"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='名字', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
    hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
    # hbook = serializers.PrimaryKeyRelatedField(label='图书', read_only=True)
    hbook = serializers.HyperlinkedRelatedField(label='图书', read_only=True, view_name='books-detail')


class BookReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ['bread']
        extra_kwargs = {
            'bread': {
                'required': True,
                'min_value': 0
            }
        }

    def update(self, instance, validated_data):
        print("BookInfoReadSerializer instance:{},validate_data:{}".format(str(instance), validated_data))
        instance.bread = validated_data['bread']
        instance.save()
        return instance
